<template>
  <div class="product-container" v-loading.fullscreen.lock="loadingPage" >
    <div id="product-product-edit"></div>
    <div class="base-form h-100-p" v-if="init">
      <product-register-edit-form
        :fields="productRegisterFields"
        :is-edit="isEdit"
        v-model="form"
        :product-register-id="productRegisterId"
        :pending='pending'
        @submit='formCheck'
        ref="editForm"
        :relationProductData="relationProductData"
        @updateRelationProductData="data => relationProductData = data"
      >
      </product-register-edit-form>

      <request-approve @createApprove="approveSubmit" ref="requestApproveDialog" />
    </div>
  </div>
</template>

<script>
/* api */
import {
  getRegisterFields,
  getRegisterDetail,
  registerUpdate,
  registerCreate
} from '@src/api/productRegisterApi'
import {
  getConfig
} from '@src/api/ProductV2Api';
/* component */
import productRegisterEditForm from './component/Edit.vue';
import RequestApprove from './component/RequestApprove.vue'
/* util */
import * as util from '@src/modules/productRegister/utils/ProductRegisterMapping';
import * as FormUtil from '@src/component/form/util';

import { getFieldValue2string } from '@service/TaskService.ts'
// import { storageGet, storageSet } from '@src/util/storage';
/* constants */
// import { PRODUCT_PRODUCT_EDIT } from '@src/component/guide/productV2Store'
import { openAccurateTab } from '@src/util/platform';
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  components: {
    [productRegisterEditForm.name]: productRegisterEditForm,
    [RequestApprove.name]: RequestApprove
  },
  // mixins: [VersionMixin, ThemeMixin],
  inject: ['initData'],
  data() {
    return {
      loadingPage: false,
      pending: false,
      init: false,
      form: {},

      dynamicProductFields: [],
      productRegister: {},
      auditOpen: false,
      relationProductData: {
        attribute: {}
      } // 以当前的字段匹配原产品数据，作为备份
    }
  },
  computed: {
    needAudit() {
      return this.auditOpen && !this.isEdit
    },
    productRegisterFields() {
      return [
        ...this.dynamicProductFields
      ]
    },
    productRegisterId() {
      let href = window.location.pathname;
      let path = '/product/register/edit/';
      let index = 0;

      if(href.indexOf(path) >= 0) {
        index = href.indexOf(path);
        return href.substr(index + path.length);
      }
      return '';
    },
    // productRegisterId() {
    //   return this.initData.id || '';
    // },
    action() {
      return this.productRegisterId ? 'edit' : 'create';
    },
    isEdit() {
      return this.action == 'edit'
    }
  },
  async mounted() {
    try {
      // 获取产品自定义字段
      let res = await getRegisterFields({isFromSetting: true});
      this.dynamicProductFields = res.data || [];
      
      // 产品编号限制字数最大长度为100
      this.dynamicProductFields.forEach(field => {
        if (field.fieldName == 'serialNumber') {
          field.maxlength = 100
        }
      })
    } catch (e) {
      console.error('product-register-add_edit fetch product fields error', e);
    }

    // 初始化默认值
    let form = {};
    if (this.isEdit) {
      // 处理编辑时数据
      this.loadingPage = true;
      let res = await getRegisterDetail({id: this.productRegisterId});

      this.loadingPage = false;

      if(res.data?.id) {
        form = res.data
        this.productRegister = form
        form.productChecked = true
        let data = this.detailData(this.productRegisterFields, form)
        form = data[0]
        this.relationProductData = data[1]
      }

    }

    // form = util.packToForm(this.productRegisterFields, form, this.isEdit);

    /**
     * 初始化所有字段的初始值
     * @param {*} fields 字段
     * @param {*} origin 原始值
     * @param {*} target 待合并的值
     */
    this.form = FormUtil.initialize(this.productRegisterFields, form);

    // if (storageGet(PRODUCT_PRODUCT_EDIT) && storageGet(PRODUCT_PRODUCT_EDIT) > 0) this.$Guide().destroy('product-product-edit')
    // else this.$Guide([{
    //   content:
    //       '在这里选择需要关联的产品类型',
    //   haveStep: false,
    //   nowStep: 1,
    //   id: 'product-product-edit',
    //   domId:'form-related-catalog',
    //   finishBtn: 'ok',
    // }], 0, '', (e) => {
    //   return new Promise((resolve, reject) => {
    //     resolve()
    //   })
    // }).create().then(res_=>{if(res_)storageSet(PRODUCT_PRODUCT_EDIT, '1')})

    this.init = true;
    this.getConfig()
  },

  methods: {
    detailData(fields, data) {
      // 待还原成产品字段的数据
      let relationInfo = {
        attribute: {}
      }

      let dataClone = {
        ...data,
        attribute: {...data.attribute}
      }
      let relationProductData = {
        attribute: {}
      }
      FormUtil.expandField(fields).forEach(field => {
        if (field.formType !== 'relationProduct') return
        let fieldName = field.fieldName
        let relationFieldName = field.setting?.fieldName
        let relationFormType = field.setting?.formType

        let dataCloneObj = fieldName.startsWith('field_') ? dataClone.attribute : dataClone
        let relationInfoObj = relationFieldName.startsWith('field_') ? relationInfo.attribute : relationInfo

        // 原数据
        let objData = relationFieldName.startsWith('field_') ? (dataClone.attribute || {})[fieldName] : dataClone[fieldName]
        relationInfoObj[relationFieldName] = objData

        // 字符串数据
        let strData = getFieldValue2string(relationInfo, relationFieldName, relationFormType, [], false)

        dataCloneObj[fieldName] = strData
        
        if (fieldName.startsWith('field_')) {
          relationProductData.attribute[fieldName] = objData
        }
      })
      return [dataClone, relationProductData]
    },
    async getConfig() {
      let res = await getConfig({
        configCode: [
          'REGISTRATION_APPROVE'
        ]
      })
      if (res.data && res.data[0]) {
        this.auditOpen = !!res.data[0].isOpen
      }
    },

    formCheck() {
      if (!this.form.productChecked) {
        this.$platform.notification({
          type: 'error',
          title: this.$t('common.validate.validateError'),
          message: this.$t('common.validate.inputValidProductRegister'),
        })
        return
      }
      
      this.$refs.editForm.validate().then(valid => {
        if(!valid) return
        if (this.needAudit) {
          this.$refs.requestApproveDialog.open();
        } else {
          this.submit()
        }
      })
    },
    approveSubmit(remark, callback) {
      this.$refs.requestApproveDialog.close();
      this.submit(remark).finally(() => {
        callback(false)
      })
    },
    submit(remark) {
      this.form.id = this.productRegisterId
      
      let form = {}
      this.productRegisterFields.forEach(v => {
        form[v.fieldName] = this.form[v.fieldName]
      })
      
      const submitForm = disposeFormSubmitTime(this.productRegisterFields, this.form)

      // const params = form
      let params = util.packToProductRegister(this.productRegisterFields, submitForm) || {}
      params = this.globalFormSubmissionDataProcessingHandler(this.productRegisterFields, params)

      let attribute = Object.assign(params.attribute || {}, this.relationProductData.attribute || {})
      Object.assign(params, this.relationProductData)
      params.attribute = attribute

      remark && (params.auditRemark = remark)

      !this.needAudit && this.toggleLoading(true)

      let fn = this.action === 'create' ? registerCreate : registerUpdate
      
      return fn(params)
        .then(res => {
          let action = this.action === 'create' ? this.$t('common.base.create') : this.$t('common.base.update')

          if (!res.succ) {
            return this.$platform.notification({
              title: this.$t('product.register.registerFailed', {action: action}),
              message: res.message || '',
              type: 'error',
            })
          }

          this.$platform.notification({
            title: this.$t('product.register.registerSuccess', {action: action}),
            type: 'success',
          })

          this.goProductRegisterView(res.data || this.productRegisterId, true)
        })
        .catch(err => {
          console.error(err);
        })
        .finally(()=>{
          !this.needAudit && this.toggleLoading(false)
        })
    },
    // 跳转产品注册信息详情
    goProductRegisterView(id, closeSelf) {
      const ids = window.frameElement.dataset.id;
      let fromId = window.frameElement.getAttribute("id");
      this.$platform.closeTab(ids);

      // let tabId = `product_register_detail_${id}`
      // this.$platform.openTab({
      //   id: tabId,
      //   title: "产品注册信息",
      //   close: true,
      //   url: `/product/register/detail/${id}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductRegisterDetail,
        key: id,
        fromId
      })
      if(closeSelf) {
        let currTabId = window.frameElement.dataset.id;
        currTabId !== tabId && this.$platform.closeTab(id);
      }
    },
    dialogBind(e){
      this.form['qrcodeId'] = e.qrcodeId;
      this.submit();
    },
    goBack() {
      if(this.action == 'create') {
        let id = window.frameElement.dataset.id;
        return this.$platform.closeTab(id);
      }
      parent.frameHistoryBack(window);
    },
    toggleLoading(loading = true) {
      this.pending = loading
      this.loadingPage = loading
    },
  }
}
</script>

<style lang="scss">
body {
  padding: 10px;
}

.product-container {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;
    display: flex;
    justify-content: space-between;

    .iconfont {
      font-size: 12px;
    }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }
}

.form-builder {
  margin: 22px auto 0;
  width: 700px;
  padding: 10px 0 0 10px;

  .input-and-btn {
    display: flex !important;
    flex-flow: row nowrap;

    .form-item,
    .form-text,
    .form-select,
    .biz-team-select {
      flex: 1;
    }

    .base-dist-picker {
      padding-right: 0;
    }

    button {
      margin-left: 10px;
    }
  }
}
</style>
